import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Tag, Space, Modal, message, Avatar } from 'antd';
import React, { useRef, useState } from 'react';

type User = {
  id: number;
  nickname: string;
  avatar: string;
  gender: 'male' | 'female' | 'unknown';
  phone: string;
  registerTime: string;
  lastLoginTime: string;
  status: 'active' | 'inactive' | 'blocked';
  postCount: number;
  followCount: number;
  followerCount: number;
};

const statusMap = {
  active: { text: '正常', color: 'green' },
  inactive: { text: '未激活', color: 'orange' },
  blocked: { text: '已封禁', color: 'red' },
};

const Users: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState<User[]>([]);

  // 模拟数据
  const mockUsers: User[] = Array.from({ length: 50 }).map((_, index) => ({
    id: index + 1,
    nickname: `用户${index + 1}`,
    avatar: `https://randomuser.me/api/portraits/${index % 2 ? 'women' : 'men'}/${index % 100}.jpg`,
    gender: ['male', 'female', 'unknown'][Math.floor(Math.random() * 3)] as any,
    phone: `1${Math.floor(Math.random() * 10000000000).toString().padStart(10, '0')}`,
    registerTime: new Date(Date.now() - Math.floor(Math.random() * 365) * 24 * 60 * 60 * 1000).toISOString(),
    lastLoginTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
    status: ['active', 'inactive', 'blocked'][Math.floor(Math.random() * 3)] as any,
    postCount: Math.floor(Math.random() * 100),
    followCount: Math.floor(Math.random() * 200),
    followerCount: Math.floor(Math.random() * 500),
  }));

  // 模拟请求数据
  const fetchUsers = async (params: any) => {
    const { current, pageSize, nickname, status, gender } = params;
    
    let filteredData = [...mockUsers];
    
    if (nickname) {
      filteredData = filteredData.filter(item => item.nickname.includes(nickname));
    }
    
    if (status) {
      filteredData = filteredData.filter(item => item.status === status);
    }
    
    if (gender) {
      filteredData = filteredData.filter(item => item.gender === gender);
    }
    
    const startIndex = (current - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const data = filteredData.slice(startIndex, endIndex);
    
    return {
      data,
      success: true,
      total: filteredData.length,
    };
  };

  const handleStatusChange = (ids: number[], newStatus: 'active' | 'inactive' | 'blocked') => {
    const statusText = {
      active: '激活',
      inactive: '停用',
      blocked: '封禁',
    };
    
    Modal.confirm({
      title: `确定要${statusText[newStatus]}选中的用户吗？`,
      content: '此操作将改变用户的状态',
      onOk: () => {
        message.success(`已${statusText[newStatus]}选中的用户`);
        actionRef.current?.reload();
      },
    });
  };

  const handleDelete = (ids: number[]) => {
    Modal.confirm({
      title: '确定要删除选中的用户吗？',
      content: '此操作不可恢复',
      onOk: () => {
        message.success('已删除选中的用户');
        actionRef.current?.reload();
      },
    });
  };

  const columns: ProColumns<User>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      render: (_, record) => (
        <Space>
          <Avatar src={record.avatar} size="small" />
          {record.nickname}
        </Space>
      ),
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueEnum: {
        male: { text: '男' },
        female: { text: '女' },
        unknown: { text: '未知' },
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      search: false,
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        active: { text: '正常', status: 'Success' },
        inactive: { text: '未激活', status: 'Warning' },
        blocked: { text: '已封禁', status: 'Error' },
      },
    },
    {
      title: '作品数',
      dataIndex: 'postCount',
      search: false,
    },
    {
      title: '关注数',
      dataIndex: 'followCount',
      search: false,
    },
    {
      title: '粉丝数',
      dataIndex: 'followerCount',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => message.info(`编辑用户 ${record.id}`)}>
          编辑
        </a>,
        record.status !== 'blocked' ? (
          <a key="block" onClick={() => handleStatusChange([record.id], 'blocked')}>
            封禁
          </a>
        ) : (
          <a key="unblock" onClick={() => handleStatusChange([record.id], 'active')}>
            解封
          </a>
        ),
        <a key="delete" onClick={() => handleDelete([record.id])}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<User>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={() => message.info('新建用户')}
            icon={<PlusOutlined />}
          >
            新建
          </Button>,
        ]}
        request={fetchUsers}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space>
            <span>已选 {selectedRowKeys.length} 项</span>
            <a onClick={onCleanSelected}>取消选择</a>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space>
            <Button
              onClick={() => handleStatusChange(
                selectedRows.map(row => row.id),
                'active'
              )}
            >
              批量激活
            </Button>
            <Button
              onClick={() => handleStatusChange(
                selectedRows.map(row => row.id),
                'blocked'
              )}
            >
              批量封禁
            </Button>
            <Button
              danger
              onClick={() => handleDelete(selectedRows.map(row => row.id))}
            >
              批量删除
            </Button>
          </Space>
        )}
      />
    </PageContainer>
  );
};

export default Users; 